<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/home/cultivateBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="培训中心" :showBack="true"></cusHeaderVue>
		<view class="contBox" :style="{ paddingTop: `calc(${scrollerHeight} + 100rpx)` }">
			<view class="contInpt">
				<image src="/static/home/searchIcon.png" mode=""></image>
				<input type="text" v-model="searchKeyword" placeholder="请输入关键词搜索" @confirm="handleSearch" />
				<view v-if="searchKeyword" class="clear-btn" @click="searchKeyword = ''">
					<text>×</text>
				</view>
			</view>
			<view class="contSxBtn" :class="indexTag != '-1' ? 'contSxBtnA' : ''" @click="markFlag = !markFlag">
				筛选
				<image src="/static/home/shaixun.png" mode=""></image>
			</view>
		</view>

		<view class="markBig" :style="{ height: swiperHeightMark }" @click="markFlag = false" v-if="markFlag">
			<view class="markBox" @click.stop>
				<view class="markList">
					<view class="markLi" :class="index==indexTag?'markLiA':''" v-for="(item,index) in tagList" :key="index" @click="indexTag = index.toString()">
						{{item}}
					</view>
				</view>
				<view class="markBtn">
					<view class="markBtnLi" @click="resetFilter">
						重置
					</view>
					<view class="markBtnLi markBtnLiA" @click="confirmFilter">
						确认
					</view>
				</view>
			</view>
		</view>
		<view class="contBoxBig">
			<scroll-view scroll-y="true" :style="{ height: swiperHeight }" @scrolltolower="loadMore"
				@refresherpulling="onRefresh" @refresherrefresh="onRefresh"
				refresher-enabled="true" refresher-threshold="90" refresher-default-style="black">
				<view class="listBox">
					<!-- 加载中提示 -->
					<view v-if="isRefreshing" class="loading-tip">
						正在刷新...
					</view>

					<!-- 课程列表 -->
					<view class="listLi" v-for="(item, index) in courseList" :key="item.id || index"
						@click="toUrl(`/pages/index/cultivateXq?id=${item.id}`)">
						<view class="listTop">
							<view class="listTag " :class="item.cursesType == 1 ? 'listTagA' : ''">
								{{ item.cursesType == 2 ? '门店宣讲' : '课件学习' }}
							</view>
							<view class="listName">
								{{ item.title || '未命名课程' }}
							</view>
						</view>
						<view class="listCont">
							<view class="listContName">
								培训简介
							</view>
							<view class="listContMsg">
								{{ item.description || '暂无简介' }}
							</view>
						</view>
						<view class="listBottom">
							<view class="listTime">
								{{ item.createTime  }}
							</view>
							<view class="listStat">
								<view class="statLi">
									<image src="/static/icon/view.png" mode="widthFix"></image>
									<text>{{ getViewCount(item) }}</text>
								</view>
								<view class="statLi">
									<image src="/static/home/pinglun.png" mode="widthFix"></image>
									<text>{{ getCommentCount(item) }}</text>
								</view>
								<view class="statLi">
									<image src="/static/home/peixundianzan.png" mode="widthFix"></image>
									<text>{{ getLikeCount(item) }}</text>
								</view>
							</view>
							<view class="listBtnBox">
								立即学习
							</view>
						</view>
					</view>

					<!-- 加载更多提示 -->
					<view v-if="isLoading && !isRefreshing" class="loading-tip">
						正在加载更多...
					</view>

					<!-- 无数据提示 -->
					<view v-if="courseList.length === 0 && !isRefreshing && !isLoading" class="empty-tip">
						暂无课程数据
					</view>
				</view>
			</scroll-view>
		</view>
	
</view>
</template>

<script setup>
import cusHeaderVue from '@/components/cus-header.vue';
import {
	ref,
	onMounted,
	reactive,
	getCurrentInstance
} from 'vue';
import {
	onLoad,

} from '@dcloudio/uni-app';
import {GETTrainingList} from '@/api/interface.js';
import { timestampToYearMonthDay } from '@/utils/date.js';

// 状态管理
const scrollerHeight = ref('');
const swiperHeight = ref('');
const swiperHeightMark = ref('');
const markFlag = ref(false);
const indexTag = ref('-1');
const searchKeyword = ref('');
const tagList = ref(['门店宣讲','课件学习']);
const courseList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = ref(1);
const isLoading = ref(false);
const isRefreshing = ref(false);

// 统计字段兼容
const getViewCount = (item) => Number(item?.ckNum ?? item?.viewCount ?? item?.viewNum ?? item?.browseCount ?? 0);
const getCommentCount = (item) => Number(item?.commentCount ?? item?.plNum ?? item?.comments ?? 0);
const getLikeCount = (item) => Number(item?.likeCount ?? item?.dzNum ?? item?.likes ?? 0);

// 生命周期
onLoad(() => {
	getBarHeight();
	fetchCourses();
})

// 跳转到课程详情页
const toCourseDetail = (courseId) => {
	uni.navigateTo({
		url: `/pages/index/cultivateXq?id=${courseId}`
	});
}

// 获取状态栏高度
const getBarHeight = () => {
	uni.getSystemInfo({
		success: function (resu) {
			scrollerHeight.value = resu.statusBarHeight + 'px'
			const query = uni.createSelectorQuery();
			query.select('.contBoxBig').boundingClientRect();
			query.exec(res => {
				swiperHeight.value = resu.windowHeight - res[0].top - resu.safeAreaInsets
					.bottom - resu.statusBarHeight - 55 + 'px';
				swiperHeightMark.value = resu.windowHeight - res[0].top + 'px';
			});
		}
	});
}

	// 课程数据获取
	const fetchCourses = async (refresh = false) => {
		console.log(1)

		if (isLoading.value && !refresh) return;
		console.log(2)
		console.log(isRefreshing.value)
		console.log(isLoading.value)

		if (refresh) {
			currentPage.value = 1;
			isRefreshing.value = true;
		} else {
			isLoading.value = true;
		}
		console.log(2)

		try {
			// 构建请求参数
			const params = {
				page: currentPage.value,
				size: pageSize.value,
				title: searchKeyword.value.trim(),
				status:1

			};

			// 添加分类筛选（只在选择了分类时添加）
			if (indexTag.value !== '-1') {
				params.cursesType = tagList.value[indexTag.value]=="门店宣讲"?2:1;
			}

			// 调用API - 使用GETTrainingList接口
			const res = await GETTrainingList(params);

			if (res.code === 0 && res.data) {
				const data = res.data;
				totalPages.value = Math.ceil(data.total / pageSize.value);
				
				// 格式化课程列表中的createTime
				const formattedList = (data.list || []).map(course => ({
					...course,
					createTime: timestampToYearMonthDay(course.createTime)
				}));

				if (refresh) {
					courseList.value = formattedList;
				} else {
					courseList.value = [...courseList.value, ...formattedList];
				}
			}
		} catch (error) {
			console.error('获取课程数据失败:', error);
			uni.showToast({
				title: '数据加载失败',
				icon: 'none'
			});
		} finally {
			isLoading.value = false;
			isRefreshing.value = false;
		}
	};

	// 搜索处理
	const handleSearch = () => {
		fetchCourses(true);
	};

	// 筛选确认
	const confirmFilter = () => {
		markFlag.value = false;
		fetchCourses(true); // 点击确认后搜索，包含选中的过滤条件
	};

	// 重置筛选
	const resetFilter = () => {
		indexTag.value = '-1'; // 重置后不包含这两个过滤条件
	};

	// 加载更多
	const loadMore = () => {
		if (currentPage.value < totalPages.value && !isLoading.value) {
			currentPage.value++;
			fetchCourses();
		}
	};

	// 下拉刷新
	const onRefresh = () => {
		fetchCourses(true);
	};

	// 页面跳转
	const toUrl = (data) => {
		uni.navigateTo({
			url: data
		})
	}
// 
</script>

<style lang="scss" scoped>
.content {
	width: 100%;
	height: 100vh;
}

.bgColor {
	width: 750rpx;
	height: 740rpx;
	position: absolute;
	z-index: -1;

	image {
		width: 100%;
		height: 100%;
	}
}

.contBox {
	width: 100%;
	padding: 22rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;

	.contInpt {
		flex: 1;
		height: 70.51rpx;
		border-radius: 35.26rpx 35.26rpx 35.26rpx 35.26rpx;
		background: #ffffff;
		box-shadow: 0.64rpx 1.28rpx 13.46rpx 0 #e19a2e29;
		display: flex;
		align-items: center;
		padding: 0 26rpx;
		box-sizing: border-box;

		image {
			width: 30.13rpx;
			height: 30.13rpx;
		}

		input {
			flex: 1;
			font-weight: 400;
			font-size: 28.21rpx;
			color: #BBC0CB;
			margin-left: 12rpx;
		}

		.clear-btn {
			width: 30rpx;
			height: 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				font-size: 32rpx;
				color: #999;
				font-weight: bold;
			}
		}
	}

	.contSxBtn {
		font-weight: 500;
		font-size: 28.21rpx;
		color: #1C2027;
		margin-left: 29rpx;
		display: flex;
		align-items: center;

		image {
			width: 28.83rpx;
			height: 28.85rpx;
			margin-left: 8rpx;
		}
	}

	.contSxBtnA {
		color: #FC6015;
	}
}

.markBig {
	width: 100%;
	background: rgba(0, 0, 0, 0.5);
	position: absolute;
	left: 0;
	z-index: 9;

	.markBox {
		width: 100%;
		border-radius: 0 0 19.23rpx 19.23rpx;
		background: #ffffff;
		padding: 27rpx 37rpx 42rpx;
		box-sizing: border-box;

		.markList {
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			/* 三等份列 */
			gap: 18rpx;

			.markLi {
				width: 212.82rpx;
				height: 68.59rpx;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #f5f6fa;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 26.92rpx;
				font-weight: 400;
				color: #222222;
			}

			.markLiA {
				color: #FC6015;
				border: 1px solid #FCA24A;
				background: #fca21521;
			}
		}

		.markBtn {
			margin-top: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.markBtnLi {
				width: 217.31rpx;
				height: 80.77rpx;
				border-radius: 40.38rpx 40.38rpx 40.38rpx 40.38rpx;
				background: #fff3e1;
				box-shadow: 0 3.85rpx 4.49rpx 0 #f9843412;
				font-size: 32.05rpx;
				font-weight: 400;
				color: #F79F31;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.markBtnLiA {
				width: 439.1rpx;
				height: 80.77rpx;
				border-radius: 40.38rpx 40.38rpx 40.38rpx 40.38rpx;
				background: linear-gradient(-90deg, #feaf38, #f98434);
				box-shadow: 0 3.85rpx 4.49rpx 0 #f984344d;
				font-size: 32.05rpx;
				font-weight: 400;
				color: #FFFFFF;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
}

.contBoxBig {
	padding: 10rpx 22rpx;
	box-sizing: border-box;

	.listBox {
		.listLi {
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			padding: 37rpx 26rpx 24rpx;
			box-sizing: border-box;
			margin-bottom: 20rpx;
			position: relative;

			.listTop {
				display: flex;
				align-items: center;

				.listTag {
					width: 113.46rpx;
					height: 38.46rpx;
					border-radius: 6.41rpx 6.41rpx 6.41rpx 6.41rpx;
					background: linear-gradient(-90deg, #ff7b44, #fe9d35);
					box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #ff7c433b;

					font-weight: 500;
					font-size: 23.08rpx;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.listTagA {
					background: linear-gradient(-90deg, #83acfa, #91d0fe);
					box-shadow: 2.56rpx 4.49rpx 10.9rpx 0.64rpx #83adfa3b;
				}

				.listName {
					font-weight: 500;
					font-size: 32.05rpx;
					color: #1C2027;
					margin-left: 12rpx;
				}
			}

			.listCont {
				margin-top: 26rpx;
				width: 100%;
				border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
				background: #f4f6f9;
				padding: 26rpx 24rpx;
				box-sizing: border-box;
				display: flex;

				.listContName {
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
				}

				.listContMsg {
					color: #222222;
					font-weight: 400;
					font-size: 24.36rpx;
					margin-left: 13rpx;
					flex: 1;
				}
			}

			.listBottom {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 26rpx;

				.listTime {
					font-size: 23.08rpx;
					font-weight: 400;
					color: #7F8494;
				}

				.listStat {
					display: flex;
					align-items: center;
					gap: 20rpx;
					color: #7F8494;
					font-size: 23.08rpx;
					.statLi { display: flex; align-items: center; }
					.statLi image { width: 26rpx; height: 26rpx; margin-right: 8rpx; }
				}

				.listBtnBox {
					width: 160rpx;
					height: 60rpx;
					border-radius: 30rpx;
					background: linear-gradient(-90deg, #feaf38, #f98434);
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 26.92rpx;
					font-weight: 500;
					color: #FFFFFF;
					box-shadow: 0 2rpx 6rpx 0 rgba(249, 132, 52, 0.2);
					transition: transform 0.2s, box-shadow 0.2s;
				}
				
				.listBtnBox:active {
					transform: scale(0.95);
					box-shadow: 0 1rpx 3rpx 0 rgba(249, 132, 52, 0.3);
				}
			}
		}
	}
}
</style>